#include "spi.h"

void SPI_Init(void)
{
    RCC->APB2ENR |= RCC_APB2ENR_IOPAEN;

    GPIOA->CRL |= GPIO_CRL_MODE4;
    GPIOA->CRL &= GPIO_CRL_CNF4;

    GPIOA->CRL |= GPIO_CRL_MODE5;
    GPIOA->CRL &= GPIO_CRL_CNF5;

    GPIOA->CRL |= GPIO_CRL_MODE7;
    GPIOA->CRL &= GPIO_CRL_CNF7;

    GPIOA->CRL &= ~GPIO_CRL_MODE6;
    GPIOA->CRL &= ~GPIO_CRL_CNF6_1;
    GPIOA->CRL |= GPIO_CRL_CNF6_0;

    SCK_LOW;

    CS_HIGH;

    SPI_DELAY;
}

void SPI_Start(void)
{
    CS_HIGH;
}

void SPI_Stop(void)
{
    CS_LOW;
}

uint8_t SPI_SwapByte(uint8_t byte)
{
    uint8_t rbyte = 0x00;

    for (uint8_t i = 0; i < 8; i++)
    {
        if (byte & 0x80)
        {
            MOSI_HIGH;
        }
        else
        {
            MOSI_LOW;
        }
        byte <<= 1;

        SCK_HIGH;
        SPI_DELAY;

        rbyte <<= 1;
        if (MISO_READ)
        {
            rbyte |= 0x01;
        }
    
        SCK_LOW;
        SPI_DELAY;
    }
    
    return rbyte;
}